package com.health.viewscontrols.medical.device.ah;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothGatt;
import android.os.Handler;
import android.util.Log;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.health.R;
import com.health.viewscontrols.NovaApplication;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.inuker.bluetooth.library.Contast;
import com.inuker.bluetooth.library.ZBleManager;
import com.inuker.bluetooth.library.interFace.IBleConnectStatusListener;
import com.inuker.bluetooth.library.interFace.IBleIndicateListener;
import com.inuker.bluetooth.library.interFace.IBleScanListener;
import com.inuker.bluetooth.library.interFace.IBleWriteListener;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.model.BleGattService;
import com.inuker.bluetooth.library.search.SearchResult;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.views.twj.StringUtil;
import com.novabluetooth.views.twj.TwjConstans;
import com.novabluetooth.views.twj.ZHexUtil;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class AHAolActivity extends BaseDeviceActivity {

    private String mType = "";
    private String mSnNumber;
    private ZBleManager mBleManager;
    private boolean isConnect = false;
    private int ThermoModel = 0;//0老体温计    1体温计E123
    boolean first = true;//只发一次信息包
    private String macAddress = "";


    private boolean isScanning = false;
    private boolean isAutoConnect = false;
    private String mMac;
    private SearchResult mDevice;
    private boolean isEnableGetValue = true;

    @Override
    public void doBusiness() {
        tv_operation_tips.setText(com.nova.health.ble.R.string.ah_aal);
        BleManager.getInstance().init(getApplication());
        mBleDevice.setDevice_Service_UUID(UUID.fromString(TwjConstans.GATT_SERVICE_PRIMARY));
        mBleDevice.setDevice_Notify_UUID(UUID.fromString(TwjConstans.CHARACTERISTIC_READABLE));
        mBleDevice.setDEVICE_write_UUID(UUID.fromString(TwjConstans.CHARACTERISTIC_WRITEABLE));

        mBleManager = ZBleManager.getInstance();
        mBleManager.initBle(this);
        startDevice();
    }

    @Override
    public void startDevice() {
        bleScan();
//        if (!isConnected) {
//            mBleDevice.setConnect(true);
//            mBleDevice.setMAC(deviceEnum.getMac());
//            mBleDevice.connect(deviceEnum.getMac());
//
//            showProgressDialog("正在连接"+ deviceEnum.getTitle());
//
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    connectionTwjBle(deviceEnum.getMac());
//                }
//            },3200);
//        } else {
//            ToastUtils.showShort("蓝牙已连接，请测量");
//        }
    }

    private void connectionTwjBle(final String mac) {
        BleManager.getInstance().connect(mac, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                Log.e(TAG,"*********开始连接**************");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.e(TAG,"*********连接失败**************");
                isConnected = false;
                blueToothState.setText("蓝牙连接失败");
                cancelProgressDialog();
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                Log.e(TAG,"*********连接成功**************");
                isConnected = true;
                blueToothState.setText("蓝牙已连接");
                cancelProgressDialog();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        byte[] data_00 = ZHexUtil.hexStringToBytes(ZHexUtil.getSendHex(0));
                        bleTwjWrite(data_00,bleDevice,TwjConstans.GATT_SERVICE_PRIMARY,
                                TwjConstans.CHARACTERISTIC_WRITEABLE);
                        bleTwjNotify(bleDevice,TwjConstans.GATT_SERVICE_PRIMARY,
                                TwjConstans.CHARACTERISTIC_READABLE);
                    }
                },300);
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                Log.e(TAG,"*********连接中断**************" + status);
                isConnected = false;
                blueToothState.setText("蓝牙已断开");
                cancelProgressDialog();
            }
        });

    }

    private void bleTwjWrite(final byte[] data, final BleDevice bleDevice, final String uuid_service,
                             String uuid_characteristic_write) {
        BleManager.getInstance().write(
                bleDevice,
                uuid_service,
                uuid_characteristic_write,
                data,
                new BleWriteCallback() {
                    @Override
                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
                        // 发送数据到设备成功
                        Log.e(TAG, "写入数据成功:" + Arrays.toString(data) );
                    }
                    @Override
                    public void onWriteFailure(BleException exception) {
                        // 发送数据到设备失败
                        Log.e(TAG, "写入数据失败:" + Arrays.toString(data) );
                    }
                });
    }

    /**
     * 订阅接受广播通知
     */
    private void bleTwjNotify(BleDevice bleDevice, String uuid_service, String uuid_characteristic_notify) {
        BleManager.getInstance().notify(
                bleDevice,
                uuid_service,
                uuid_characteristic_notify,
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        // 打开通知操作成功
                    }
                    @Override
                    public void onNotifyFailure(BleException exception) {
                        // 打开通知操作失败
                    }
                    @Override
                    public void onCharacteristicChanged(final byte[] data) {
                        // 打开通知后，设备发过来的数据将在这里出现
                        Log.e(TAG, "onCharacteristicChanged: " + "收到data==" + Arrays.toString(data)  );
                        showContent(data);
                    }
                });
    }


    @Override
    public void update(String hexStr) {
        Log.e(TAG, "update: " + hexStr );
    }

    private void showContent(byte[] data) {
        if (null == data) return;
        byte index0 = data[0];
        if (index0 != 85) return;
        byte index2 = data[2];
        if (index2 == 3) {//Device upload results
            byte[] valueArr = {data[10], data[9]};
            //10+9 Convert to decimal,And then  divide by 100,get the temperature
            String strValue = ZHexUtil.encodeHexStr(valueArr);
            int value = Integer.valueOf(strValue, 16);
            Log.e("zdw", "value --" + value);
            //跟体温计结果显示保持一致：丢弃小数点后第二位
            String valueStr = StringUtil.formatTo1ROUNDDOWN((double) value / 100);
            String str = String.format(" 温度值:%s℃", valueStr);
            tv_state.setText("获取测量结果成功");
            tv_result.setText(str);
            String results = DeviceShowSaveData.getDataShow(valueStr, TwjConstans.DEVICE_NAME);

            // 存体温
            DeviceShowSaveData.saveTiwen(valueStr);

            Log.e("showData()3333", results + "*********************");
        } else if (index2 == 5) {

        }
    }

    @Override
    public void disconnectDevice() {
        try {
            if (mDevice != null)
                ZBleManager.getInstance().destroy(mDevice.getAddress());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("CheckResult")
    private void bleScan() {
        if (isScanning) return;
        Flowable.timer(500, TimeUnit.MILLISECONDS)
                .distinct()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
//                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mBleManager.scan(new IBleScanListener() {
                            @Override
                            public void onScanStarted() {
                                Log.e("zdw", "---onScanStarted-------");
                                blueToothState.setText("开始连接蓝牙");
                                isScanning = true;
//                                progress.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onScanCanceled() {
                                Log.e("zdw", "---onScanCanceled-------");
                                isScanning = false;
                            }

                            @Override
                            public void onScanStop() {
                                Log.e("zdw", "---onScanStop-------");
                                isScanning = false;
//                                bleScan();
                            }

                            @Override
                            public void onDeviceFounded(SearchResult device) {
                                if (device == null) return;
                                if (!device.getName().contains("Bioland-IT")) return;
                                autoConnect(device);
                            }
                        });
                    }
                });

    }

    /**
     * 自动连接蓝牙
     * Automatic bluetooth connection
     */
    private void autoConnect(SearchResult device) {
        if (null == device) return;
//        isAutoConnect = true;
        if (!isConnect) {
            isConnect = true;
            mMac = device.getAddress();
            mDevice = device;
            connect(device.getAddress());
        }
    }

    /**
     * 向蓝牙发送写入数据
     * Send write data to bluetooth
     *
     * @param data 写入的byte数据(The byte data that was written)
     */
    @SuppressLint("CheckResult")
    private void write(final String mac, final byte[] data) {
        if(ThermoModel==1)
        {
            mBleManager.write(mac, Contast.GATT_SERVICE_PRIMARYNEW1,
                    Contast.CHARACTERISTIC_WRITEABLENEW1, data, new IBleWriteListener() {
                        @Override
                        public void onWriteSuccess() {
                            Log.e("zdw", getString(R.string.write_data_ok) + Arrays.toString(data));
                        }

                        @Override
                        public void onWriteFailure(int code) {
                            Log.e("zdw", getString(R.string.write_data_error) + Arrays.toString(data));
//                        showMessage("未收到测量数据，请尝试重启设备并刷新页面");
                        }
                    });
        }
        else {
            mBleManager.write(mac, Contast.GATT_SERVICE_PRIMARY,
                    Contast.CHARACTERISTIC_WRITEABLE, data, new IBleWriteListener() {
                        @Override
                        public void onWriteSuccess() {
                            Log.e("zdw", getString(R.string.write_data_ok) + Arrays.toString(data));
                        }

                        @Override
                        public void onWriteFailure(int code) {
                            Log.e("zdw", getString(R.string.write_data_error) + Arrays.toString(data));
//                        showMessage("未收到测量数据，请尝试重启设备并刷新页面");
                        }
                    });
        }
    }
    /**
     * 订阅接受广播通知
     * Subscribe to receive broadcast notifications
     */
    private void indicate() {
        if(ThermoModel==1)
        {
            mBleManager.indicate(mDevice.getAddress(), Contast.GATT_SERVICE_PRIMARYNEW1,
                    Contast.CHARACTERISTIC_READABLENEW1, new IBleIndicateListener() {
                        @Override
                        public void onIndicateSuccess() {
                            Log.e("zdw", getString(R.string.indicate_success));
                            try {
                                Thread.sleep(500L);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            //发送00信息包
                            byte[] data_00 = ZHexUtil.hexStringToBytes(getSendHex(0));
                            //refreshLogView("\n写入数据(16进制)：" + Arrays.toString(ZHexUtil.setStr(ZHexUtil.bytes2HexString(data_00, data_00.length))));

                            write(mDevice.getAddress(), data_00);
                        }

                        @Override
                        public void onIndicateFailure(int code) {
                            Log.e("zdw", getString(R.string.indicate_failure) + "，code:" + "--" + code);

                            bleScan();
                        }

                        @Override
                        public void onCharacteristicChanged(byte[] data) {
                            //refreshLogView("\n体温计返回(16进制)：" + Arrays.toString(ZHexUtil.setStr(ZHexUtil.bytes2HexString(data, data.length))));

                            Log.e("zdw", getString(R.string.get_device_data) + "--" + Arrays.toString(data));
                            cancelProgressDialog();
                            mBleManager.disConnectDevice(mMac);
                            showContent(data);
                        }
                    });

        }
        else
        {
            mBleManager.indicate(mDevice.getAddress(), Contast.GATT_SERVICE_PRIMARY,
                    Contast.CHARACTERISTIC_READABLE, new IBleIndicateListener() {
                        @Override
                        public void onIndicateSuccess() {
                            Log.e("zdw", getString(R.string.indicate_success));
                            try {
                                Thread.sleep(500L);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            //发送00信息包
                            byte[] data_00 = ZHexUtil.hexStringToBytes(getSendHex(0));
//                            refreshLogView("\n写入数据(16进制2222222222222)：" + Arrays.toString(ZHexUtil.setStr(ZHexUtil.bytes2HexString(data_00, data_00.length))));

                            write(mDevice.getAddress(), data_00);
                        }

                        @Override
                        public void onIndicateFailure(int code) {
                            Log.e("zdw", getString(R.string.indicate_failure) + "，code:" + "--" + code);
//                            tvStatus.setText(R.string.bluetooth_search);
//                            progress.setVisibility(View.VISIBLE);
                            bleScan();
                        }

                        @Override
                        public void onCharacteristicChanged(byte[] data) {
//                            refreshLogView("\n体温计返回(16进制)：" + Arrays.toString(ZHexUtil.setStr(ZHexUtil.bytes2HexString(data, data.length))));

                            Log.e("zdw11111111", getString(R.string.get_device_data) + "--" + Arrays.toString(data));
//                            getVersion(data);
//                            getBleInfo(data);
                            cancelProgressDialog();
                            mBleManager.disConnectDevice(mMac);
                            showContent(data);
                        }
                    });

        }


    }
    public static String getSendHex(int sendPack) {
        SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd-HH-mm-ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String time = sdf.format(new Date());
        String[] arrTime = time.split("-");
        if (arrTime.length == 6) {
            int index0 = 90;
            int index1 = 10;
            int index2 = sendPack;//packet category
            int index3 = Integer.parseInt(arrTime[0]);//Year
            int index4 = Integer.parseInt(arrTime[1]);//Month
            int index5 = Integer.parseInt(arrTime[2]);//Day
            int index6 = Integer.parseInt(arrTime[3]);//Hour
            int index7 = Integer.parseInt(arrTime[4]);//Minute
            int index8 = Integer.parseInt(arrTime[5]);//Second
            int index9 = index0 + index1 + index2 + index3 + index4 + index5 + index6 + index7 + index8 + 2;
            if (index9 > 255) {
                index9 = index9 % 255;
            }
            byte[] data = new byte[]{(byte) index0, (byte) index1, (byte) index2, (byte) index3,
                    (byte) index4, (byte) index5, (byte) index6, (byte) index7, (byte) index8};

            String hexSend = ZHexUtil.encodeHexStr(data);
            String hexIndex9 = ZHexUtil.encodeHexStr(new byte[]{(byte) index9});
            int len = hexIndex9.length();
            String i9 = hexIndex9.substring(len - 2, len);
            return String.format("%s%s", hexSend, i9).toUpperCase();
        }
        return "";
    }

    @Override
    protected void onPause() {
        super.onPause();
        ZBleManager.getInstance().cancelScan();
    }

    /**
     * 根据mac连接蓝牙
     * Connect to bluetooth according to MAC
     *
     * @param mac MAC address
     */
    private void connect(String mac) {
        mBleManager.connect(mac, new IBleConnectStatusListener() {
            @Override
            public void onStartConnect() {
                isConnect = true;
                blueToothState.setText("开始连接蓝牙");
                isConnect = true;
                mBleManager.cancelScan();

            }

            @Override
            public void onConnectFail() {
                Log.e("zdw", "---onConnectFail");
                isConnect = false;
                blueToothState.setText("连接蓝牙失败");
//                refreshList(true);
            }

            @Override
            public void onConnectSuccess(int code, BleGattProfile data, String mac) {
                Log.e("zdw", "---onConnectSuccess");
                ThermoModel = 0;
                for (BleGattService s : data.getServices()) {
                    if (s.getUUID().toString().equals(Contast.GATT_SERVICE_PRIMARYNEW1)) {
                        ThermoModel = 1;
                        break;
                    }
                }
                indicate();
                isConnect = true;
                blueToothState.setText("连接蓝牙成功");
                showProgressDialog("等待接收数据");
                isEnableGetValue = true;
            }

            @Override
            public void onDisConnected(String mac) {
                Log.e("zdw", "---onDisConnected");
                isConnect = false;
                blueToothState.setText("蓝牙连接已取消");
//                bleScan();
            }
        });
    }

//    private void showContent(byte[] data) {
//        if (null == data) return;
//        byte index0 = data[0];
//        if (index0 != 85) return;
//        byte index2 = data[2];
//        if (index2 == 3) {//Device upload results
//            byte[] valueArr = {data[10], data[9]};
//            //10+9 Convert to decimal,And then  divide by 100,get the temperature
//            String strValue = ZHexUtil.encodeHexStr(valueArr);
//            int value = Integer.valueOf(strValue, 16);
//            Log.e("zdw", "value --" + value);
//            //跟体温计结果显示保持一致：丢弃小数点后第二位
//            String valueStr = StringUtil.formatTo1ROUNDDOWN((double) value / 100);
//            String str = String.format(" 温度值:%s℃", valueStr);
////            tv_state.setText("获取测量结果成功");
//            tv_result.setText(valueStr);
//            String results = DeviceShowSaveData.getDataShow(valueStr, TwjConstans.DEVICE_NAME);
//
//            // 存体温
//            DeviceShowSaveData.saveTiwen(valueStr);
//
//            Log.e("showData()3333", results + "*********************");
//        } else if (index2 == 5) {
//
//        }
//    }
}
